<?php
namespace app\admin\controller\system;
use app\common\annotation\NodeAnnotation;
use app\common\controller\Admin;
use app\common\logic\MenuLogic;
use think\Console;
use think\facade\Cache;
use think\facade\Cookie;
use think\Request;

/**
 * @NodeAnnotation(
 *     title="菜单管理",
 *     parent="admin/system.setting",
 *     is_menu=0
 * )
 * Class Menu
 * @package app\admin\controller
 */
class Menu extends Admin
{
    protected $model;

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\system\Menu();
    }

    /**
     * @NodeAnnotation(
     *     title="菜单列表",
     *     parent="admin/system.menu",
     *     MenuRoot="admin/system.setting"
     * )
     */
    public function index(Request $request)
    {

        $keywords  = $request->param("keywords");

        $where = [];

        if($keywords) array_push($where,['title',"like","%$keywords%"]);


        if($request->isAjax())
        {
            $menuList = $this->model->where($where)->select();

            $this->success("success","",$menuList);
        }

        $menuList = $this->model->where($where)->paginate();

        $this->assign([
            "menuList" => $menuList,
            "search"   => [
                "keywords" => $keywords
            ]
        ]);

        return $this->fetch();
    }


    /**
     * @NodeAnnotation(
     *     title="导入菜单",
     *     parent="admin/system.menu",
     *     is_menu=0
     * )
     */
    public function importmenu()
    {
        $apps = scan_dir(app_path() . '*', GLOB_ONLYDIR);
        $app = $this->request->param('app', '');

        array_unique($apps);
        unset($apps[array_search("common", $apps)]);
        unset($apps[array_search("http", $apps)]);
        sort($apps);

        if (empty($app)) {
            $app = $apps[0];
        }

        if (!in_array($app, $apps)) {
            $this->error('应用' . $app . '不存在!');
        }

        $newMenus = MenuLogic::importMenu([$app]);

        $index = array_search($app, $apps);

        $nextIndex = $index + 1;

        $nextIndex = $nextIndex >= count($apps) ? 0 : $nextIndex;

        if ($nextIndex) {
            $this->assign("next_app", $apps[$nextIndex]);
        }

        $this->assign("app", $app);
        $this->assign("new_menus", $newMenus);

        return $this->fetch();
    }


    /**
     * @NodeAnnotation(
     *     title="更新菜单",
     *     parent="admin/system.node",
     *     is_menu=0,
     * )
     */
    public function refmenu()
    {
        $apps = scan_dir(app_path() . '*', GLOB_ONLYDIR);
        $app = $this->request->param('app', '');

        array_unique($apps);
        unset($apps[array_search("common", $apps)]);
        unset($apps[array_search("http", $apps)]);
        sort($apps);

        if (empty($app)) {
            $app = $apps[0];
        }

        if (!in_array($app, $apps)) {
            $this->error('应用' . $app . '不存在!');
        }

        $newMenus = MenuLogic::updateMenu([$app]);

        $index = array_search($app, $apps);

        $nextIndex = $index + 1;

        $nextIndex = $nextIndex >= count($apps) ? 0 : $nextIndex;

        if ($nextIndex) {
            $this->assign("next_app", $apps[$nextIndex]);
        }

        $this->assign("app", $app);
        $this->assign("new_menus", $newMenus);

        return $this->fetch();
    }

    /**
     * @NodeAnnotation(
     *     title="修改菜单",
     *      parent="admin/system.menu",
     *     is_menu=0
     * )
     */
    public function savemenu(Request $request)
    {
        if($request->isAjax())
        {
            $dataType = $request->param("menuType");
            if($dataType && $dataType=='tree')
            {
                $TreeMenu = $this->model->getMenu();
                return json($TreeMenu);
            }

            $input  = $request->post();
            if(isset($input['file'])) unset($input['file']);
            $result = $this->model->saveMenu($input);

            if($result)
            {
                $this->success("修改成功","",$input);
            }else{
                $this->error('修改失败');
            }
        }
        $id = $request->param("id",0,'intval');

        $menu = $this->model
            ->field("id,url_link as href,name,title as text,icon ,is_view as hasView,parent_id,status,is_view")
            ->find($id);

        $level = $this->model->field("id,url_link as href,name,title as text,icon ,is_view as hasView,parent_id,status,is_view")
            ->find($menu['parent_id']);;

        $this->assign([
            'menu'  => $menu,
            "level" => $level
        ]);

        return $this->fetch();
    }

    /**
     * @NodeAnnotation(
     *     title="获取菜单",
     *      parent="admin/system.menu",
     *     is_view=0,
     *     is_menu=0,
     *     auth=0
     * )
     */
    public function getmenu(Request $request)
    {

        $id = $request->param("id",0,"intval");

        //刷新菜单指令
        $refMenu = $request->param("refMenu",0,'intval');
        if($refMenu==1)
        {
//          //Console::call("clear");
            $userId = get_user("id");
            Cache::rm($userId."_menuList");
            Cache::rm($userId."_nodeList");
            return true;
        }

        //$MenuList = $this->model->getMenu();

        $MenuList = get_access_menu();

        if ($id)
        {
            $data = $this->model->findMenu($id);

            $MenuList = (new MenuLogic())->getTreeSon($MenuList,$data['id']);
        }
        return json( (new MenuLogic())->getTree($MenuList));
    }

    /**
     * @NodeAnnotation(
     *     title="添加菜单",
     *     parent="admin/system.menu",
     *     is_menu=0
     * )
     */
    public function add(Request $request)
    {
        if ($request->isAjax())
        {
            $dataType = $request->param("menuType");
            if($dataType && $dataType=='tree')
            {
                $TreeMenu = $this->model->getMenu();
                return json($TreeMenu);
            }
            $input = $request->post();
            if(isset($input['file'])) unset($input['file']);
            if($input && $res = $this->model->addMenu($input))
            {
                $this->success("添加成功",url("admin/system.menu/savemenu",['id'=>$res['id']]),$input);
            }else{
                $this->error("添加失败");
            }
        }
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(
     *     title="删除菜单",
     *      parent="admin/system.menu",
     *     is_view=0,
     *     is_menu=0
     * )
     */
    public function delmenu(Request $request)
    {
        $idList = $request->param("idList");
        if($idList)
        {
            $result = $this->model->delMenu([["id","in",$idList]]);
            if($result)
            {
                $this->success("删除成功");
            }else{
                $this->error("删除失败");
            }
        }else{
            $this->error("请选择所需要删除的数据");
        }
    }

}